package com.scs.application.modules.wm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.scs.application.core.exception.BusinessException;
import com.scs.application.core.service.BaseServiceImpl;
import com.scs.application.core.utils.StringUtils;
import com.scs.application.modules.base.entity.Matr;
import com.scs.application.modules.base.entity.MatrUnit;
import com.scs.application.modules.base.mapper.MatrMapper;
import com.scs.application.modules.base.mapper.MatrUnitMapper;
import com.scs.application.modules.purchase.enums.PurchaseType;
import com.scs.application.modules.wm.entity.Transfer;
import com.scs.application.modules.wm.entity.TransferDemand;
import com.scs.application.modules.wm.mapper.TransferDemandMapper;
import com.scs.application.modules.wm.mapper.TransferMapper;
import com.scs.application.modules.wm.service.TransferDemandService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 调拨需求单 服务实现类
 * </p>
 */
@Service
public class TransferDemandServiceImpl extends BaseServiceImpl<TransferDemandMapper, TransferDemand> implements TransferDemandService {

    @Resource
    private MatrUnitMapper matrUnitMapper;

    @Resource
    private MatrMapper matrMapper;

    @Resource
    private TransferMapper transferMapper;

    @Override
    public boolean saveOrUpdate(TransferDemand entity) {

        // 在一张需求单内不允许同一个耗材
        List<TransferDemand> items = this.list(Wrappers.<TransferDemand>query()
                .eq("transfer_id", entity.getTransferId())
                .eq("matr_id", entity.getMatrId())
                .ne(StringUtils.isNotBlank(entity.getId()), "id", entity.getId()));

        if (!items.isEmpty()) {
            throw new BusinessException("需求单中耗材不允许重复");
        }
        Matr matr = matrMapper.selectById(entity.getMatrId());
        Transfer transfer = transferMapper.selectById(entity.getTransferId());
        if (StringUtils.isBlank(transfer.getTransferType())) {
            transfer.setTransferType(matr.getBaseType());
            transferMapper.updateById(transfer);
        } else if (!transfer.getTransferType().equals(matr.getBaseType())) {
            throw new BusinessException("该调拨单的调拨类型是%s，不能添加其他类型的需求", transfer.getTransferType());
        }
//        if (StringUtils.isNotBlank(entity.getId()) && StringUtils.isNotBlank(entity.getBillPackageUnit())) {
//            Transfer transfer = transferMapper.selectById(entity.getTransferId());
//            QueryWrapper queryWrapper = Wrappers.<Stock>query().eq("matr_id", entity.getMatrId()).in("warehouse_id", transfer.getFromWarehouseId());
//            List<StockGroupWarehouseMatrDTO> stockGroupWarehouseMatrDTOS= stockService.getListGroupByMatr(queryWrapper);
//            if (stockGroupWarehouseMatrDTOS == null || stockGroupWarehouseMatrDTOS.size() < 1) {
//                throw new BusinessException("该耗材已无库存，不允许开单");
//            }
//            List<StockGroupWarehouseMatrDTO> stockGroupWarehouseMatrDTOSDind = stockGroupWarehouseMatrDTOS.stream().filter(ob -> ob.getPackageUnit().equals(entity.getBillPackageUnit())).collect(Collectors.toList());
//
//            if (stockGroupWarehouseMatrDTOS == null || stockGroupWarehouseMatrDTOS.size() < 1) {
//                throw new BusinessException("该耗材该开单单位没有可用库存，请开单其他单位");
//            }
//
//            double PackageQtyUseSum = UtilNum.getDouble(stockGroupWarehouseMatrDTOSDind.stream().mapToDouble(ob -> ob.getPackageQtyUse()).sum());
//
//            if (entity.getBillPackageQty()  > PackageQtyUseSum)
//                throw new BusinessException("该耗材该单位开单数量[%s]已超过可用库存[%s]，请重新修改开单单位或者数量",entity.getBillPackageQty(),PackageQtyUseSum);
//        }
        return super.saveOrUpdate(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeCascadeByIds(Collection<? extends Serializable> idList) {
        List<TransferDemand> items = super.list(new QueryWrapper<TransferDemand>()
                .in("id", idList));
        TransferDemand transferDemand = items.get(0);
        String transferId = transferDemand.getTransferId();
        List<TransferDemand> transferDemands = super.list(new QueryWrapper<TransferDemand>()
                .eq("transfer_id", transferId));
        if (items.size() == transferDemands.size()) {
            transferMapper.updateById((Transfer) new Transfer().setTransferType("").setId(transferId));
        }
        return super.removeCascadeByIds(idList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addDtlBatch(List<TransferDemand> entityList) {
        List<String> matrIdList = entityList.stream().map(TransferDemand::getMatrId).collect(Collectors.toList());
        //所选耗材所有单位
        Map<String, List<MatrUnit>> matrUnitMap = matrUnitMapper
                .selectList(Wrappers.<MatrUnit>query().in("matr_id", matrIdList).eq("flag_apply", 1).orderByDesc("rate"))
                .stream().collect(Collectors.groupingBy(MatrUnit::getMatrId));
        ;
        if (matrUnitMap == null || matrUnitMap.size() < 1) {
            throw new BusinessException("所操作的耗材都没有可用请领单位，请重新选择");
        }

        Map<String, Matr> matrMap = matrMapper.selectList(Wrappers.<Matr>query().in("id", matrIdList)).stream().collect(Collectors.toMap(Matr::getId, matr -> matr));
        if (matrMap == null || matrMap.size() < 1) {
            throw new BusinessException("所操作的耗材已被删除，请重新选择");
        }

        Map<String, TransferDemand> demandDbMap = this.list(Wrappers.<TransferDemand>query().eq("transfer_id", entityList.get(0).getTransferId())).stream().collect(Collectors.toMap(TransferDemand::getId, transferDemand -> transferDemand));

        String transferType = PurchaseType.MATR.getKey();
        Matr matr;
        List<MatrUnit> matrUnitList;
        MatrUnit matrUnit;
        for (int i = 0; i < entityList.size(); i++) {
            matr = matrMap.get(entityList.get(i).getMatrId());
            matrUnitList = matrUnitMap.get(entityList.get(i).getMatrId());
            if (matr == null) {
                throw new BusinessException("耗材【%s】已被删除，请重新选择", entityList.get(i).getMatrName());
            }
            if (demandDbMap != null && demandDbMap.containsKey(matr.getId())) {
                throw new BusinessException("耗材【%s】已添加过，不可重复添加", entityList.get(i).getMatrName());
            }
            if (matrUnitList == null || matrUnitList.size() < 1) {
                throw new BusinessException("耗材【%s】没有可用单位，请重新选择或者请联系运营人员进行维护", entityList.get(i).getMatrName());
            }
            matrUnit = matrUnitList.get(0);
            //耗材属性
            entityList.get(i).setMatrId(matr.getId()).setMatrName(matr.getName()).setMatrSpec(matr.getSpec())
                    .setSkuPrice(matr.getSkuPrice()).setSkuUnit(matr.getSkuUnit());

            //包装属性
            entityList.get(i).setPackageUnit(matrUnit.getUnit()).setPackageRate(matrUnit.getRate()).setPackageQty(1d);
            //单品数量
            entityList.get(i).setBillSkuQty(matrUnit.getRate()).setBillAmount(matrUnit.getPrice()).setPickedSkuQty(0d);

            //开单属性
            entityList.get(i).setBillPackageUnit(matrUnit.getUnit()).setBillPackageRate(matrUnit.getRate()).setBillPackageQty(1d);
        }
        entityList.stream().forEach(item -> saveOrUpdate(item));
    }
}
